package com.stox.manager.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.stox.manager.BarManager;
import com.stox.manager.ScripManager;
import com.stox.model.entity.BarEntity;
import com.stox.repository.BarRepository;

@Component
@Transactional
public class BarManagerImpl implements BarManager {

	@Autowired
	private BarRepository barRepository;
	
	@Autowired
	private ScripManager scripManager;
	
	@Override
	public void flush() {
		barRepository.flush();
	}

	public List<BarEntity> findByScripCode(String scripCode) {
		return barRepository.findByScripCode(scripCode);
	}

	@Transactional
	public BarEntity save(BarEntity bar) {
		if(null != bar && 
				null != bar.getScrip() && 
				!scripManager.exists(bar.getScrip().getCode())){
			scripManager.saveAndFlush(bar.getScrip());
			barRepository.createPartition(bar.getScripCode());
		}
		return barRepository.save(bar);
	}

	@Transactional
	public List<BarEntity> save(List<BarEntity> bars) {
		List<BarEntity> saved = new ArrayList<BarEntity>(bars.size());
		for(BarEntity bar : bars) saved.add(save(bar));
		return saved;
	}

}
